package com.ordertracker.listener;

import org.hibernate.event.spi.PreDeleteEvent;
import org.hibernate.event.spi.PreInsertEvent;
import org.hibernate.event.spi.PreLoadEvent;
import org.hibernate.event.spi.PreUpdateEvent;
import org.hibernate.tuple.StandardProperty;

import com.ordertracker.core.PersistentEventRegister;
import com.ordertracker.persistent.constant.DictionaryState;
import com.ordertracker.persistent.dictionary.template.StateEntityTemplate;

/**
 * Description of class.
 * Created 2/22/13 1:17 PM
 *
 * @author andrey.rodin@playtech.com
 */

public class GeneralEntityListener implements EntityConstraintSupport {

    private static final long serialVersionUID = -385131958110551094L;

    private PersistentEventRegister eventRegister;

    public GeneralEntityListener(PersistentEventRegister eventRegister) {
        this.eventRegister = eventRegister;
    }

    @Override
    public boolean onPreInsert(PreInsertEvent event) {
        if (event.getEntity() instanceof StateEntityTemplate) {
            StateEntityTemplate stateEntityTemplate = (StateEntityTemplate)event.getEntity();
            if (stateEntityTemplate.getState() == null) {
                stateEntityTemplate.setState(DictionaryState.ACTIVE);
                refreshProperty(event, "state", DictionaryState.ACTIVE);
            }
        }

        return false;
    }

    @Override
    public boolean onPreDelete(PreDeleteEvent event) {
        return false;
    }

    @Override
    public void onPreLoad(PreLoadEvent event) {

    }

    @Override
    public boolean onPreUpdate(PreUpdateEvent event) {
        return false;
    }

    public void refreshProperty(PreInsertEvent event, String nameValue, Object value) {
        StandardProperty[] properties = event.getPersister().getEntityMetamodel().getProperties();
        Object[] state = event.getState();

        for (int i = 0; i < properties.length; i++) {
            if (properties[i].getName().equals(nameValue)) {
                state[i] = state[i] == null ? value : state[i];
                break;
            }
        }
    }

    @Override
    public void setPersistentEventRegister(PersistentEventRegister eventRegister) {
        this.eventRegister = eventRegister;
    }

    @Override
    public PersistentEventRegister getPersistentEventRegister() {
        return eventRegister;
    }

    @Override
    public void registerListener() {
        eventRegister.registerListeners(this);
    }
}
